<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Withdrawal;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use App\Models\Withdrawal as WithdrawalModel;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Layout\Content;
use App\Handlers\WithdrawalHandler;
use Dcat\Admin\IFrameGrid;
use App\Admin\Extensions\Tools\BatchAudit;
use App\Models\Enum\WithdrawalEnum;


class WithdrawalController extends BaseController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Withdrawal(['admin_user', 'admin_ids']), function (Grid $grid) {
            $grid->setActionClass(Grid\Displayers\ContextMenuActions::class);
            $grid = $this->gridButton($grid, true, false, false, true, true, false);

            $grid->model()->whereIn('amount_type', [1, 2]);
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                // append一个操作
                $actions->append('<a href="'.route("zbsht.withdrawal.edit",
                        $this->id).'"><i class="fa fa-paper-plane"></i>审核</a>');
                // prepend一个操作
//                $actions->prepend('<a href=""><i class="fa fa-paper-plane"></i></a>');
            });

            // 传入字符串
            //$grid->id->sortable();
            // 关闭批量删除
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });
//            <i class="fa fa-chain-broken"></i>
//            <i class="fa fa-check"></i>
            $grid->batchActions([
                new BatchAudit('&nbsp;驳回', 1),
                new BatchAudit('&nbsp;通过', 2)
            ]);
            $grid->column('admin_user.name', trans('withdrawal.fields.user_id'));
            $grid->column('admin_user.username', trans('帐号'));
            $grid->usd_amount;
            $grid->del_amount;
            $grid->rmb_amount_received;
            //$grid->rate;
            $grid->sp_status->using(WithdrawalEnum::SP_STATUS)->label(['primary', 'danger', 'success'])
                ->filter(Grid\Column\Filter\In::make(WithdrawalEnum::SP_STATUS));

            $grid->amount_type->using(WithdrawalEnum::AMOUNT_TYPE)->label([
                1 => 'success', 2 => 'primary', 3 => 'danger'
            ])->filter(Grid\Column\Filter\In::make(WithdrawalEnum::AMOUNT_TYPE));

            $grid->type->using(WithdrawalEnum::TYPE)->label([1 => 'success', 2 => 'primary'])
                ->filter(Grid\Column\Filter\In::make(WithdrawalEnum::TYPE));
//            $grid->bank_user;
//            $grid->bank_name;
//            $grid->bank_number;
//            $grid->bank_address;
            $grid->notes;
            $grid->column('admin_ids.username', '审核人');
            $grid->created_at->sortable();

            $grid->filter(function ($filter) {
                // 展开过滤器
                //$filter->expand();
                // 更改为 rightSide 布局
                $filter->panel();

                // 在这里添加字段过滤器
                $filter->like('admin_user.name', '姓名')->width(2);
                $filter->like('admin_user.username', '帐号')->width(2);
                $filter->whereBetween('created_at', function ($q) {
                    $start = $this->input['start'] ?? null;
                    $end   = $this->input['end'] ?? null;

                    $q->whereBetween('created_at', [$start, $end]);
                }, '日期')->date(1)->width(3);
            });
        });
    }


    /**
     * Index interface.
     *
     * @param  Content  $content
     *
     * @return Content
     */
    public function index(Content $content)
    {
        if (request(IFrameGrid::QUERY_NAME)) {
            return $content->body($this->iFrameGrid());
        }

        $arr = explode('/', request()->path());
        if (count($arr) == 2) {
            return $content
                ->title($this->title())
                ->description($this->description()['index'] ?? trans('admin.list'))
                ->body($this->grid());
        } else {
            return $content
                ->title(trans('withdrawal.labels.benjingrid'))
                ->description($this->description()['index'] ?? trans('admin.list'))
                ->body($this->benjinGrid());
        }

    }


    protected function benjinGrid()
    {
        return Grid::make(new Withdrawal(['admin_user', 'admin_ids']), function (Grid $grid) {
            $grid->setActionClass(Grid\Displayers\ContextMenuActions::class);
            $grid = $this->gridButton($grid, true, false, false, true, true, false);

            $grid->model()->whereIn('amount_type', [3]);
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                // append一个操作
                $actions->append('<a href="'.route("zbsht.withdrawal.edit",
                        $this->id).'"><i class="fa fa-paper-plane"></i>审核</a>');
                // prepend一个操作
//                $actions->prepend('<a href=""><i class="fa fa-paper-plane"></i></a>');
            });

            //$grid->id->sortable();
            // 关闭批量删除
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });
            $grid->batchActions([
                new BatchAudit('&nbsp;驳回', 1),
                new BatchAudit('&nbsp;通过', 2)
            ]);
            $grid->column('admin_user.name', trans('withdrawal.fields.user_id'));
            $grid->column('admin_user.username', trans('帐号'));
            $grid->usd_amount;
            $grid->del_amount;
            $grid->rmb_amount_received;
            //$grid->rate;
            $grid->sp_status->using(WithdrawalEnum::SP_STATUS)->label(['primary', 'danger', 'success'])->filter(
                Grid\Column\Filter\In::make(WithdrawalEnum::SP_STATUS)
            );
            $grid->amount_type->using(WithdrawalEnum::AMOUNT_TYPE)->label([
                1 => 'success', 2 => 'primary', 3 => 'danger'
            ])->filter(
                Grid\Column\Filter\In::make(WithdrawalEnum::AMOUNT_TYPE)
            );
            $grid->bank_user;
            $grid->bank_name;
            $grid->bank_number;
            $grid->bank_address;
            $grid->notes;
            $grid->column('admin_ids.username', '审核人');
            $grid->created_at->sortable();

            $grid->filter(function ($filter) {
                // 展开过滤器
                //$filter->expand();
                // 更改为 rightSide 布局
                $filter->panel();

                // 在这里添加字段过滤器
                $filter->like('admin_user.name', '姓名')->width(2);
                $filter->like('admin_user.username', '帐号')->width(2);
                $filter->whereBetween('created_at', function ($q) {
                    $start = $this->input['start'] ?? null;
                    $end   = $this->input['end'] ?? null;

                    $q->whereBetween('created_at', [$start, $end]);
                }, '日期')->date(1)->width(3);
            });
        });
    }


    /***
     *  重构显示页面 用Tab 方式显示多页面
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('投入记录')
            // body 方法可以接受 Laravel 的视图作为参数
            ->row(function (Row $row) use ($id) {
                $row->column(6, function (Column $column) use ($id) {
                    $column->append($this->detail($id));
                });
            });
    }


    /**
     * Make a show builder.
     *
     * @param  mixed  $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Withdrawal(['admin_ids', 'admin_user']), function (Show $show) {
            $show->disableDeleteButton();

            $show->user_id->as(function ($title) {
                // 获取当前行的其他字段
                return $this->admin_user['name'];
            });
            $show->usd_amount;
            $show->del_amount;
            $show->rmb_amount_received;
            $show->rate;
            $show->admin_ids->as(function ($title) {
                return $this->admin_id['name'];
            });
            $show->sp_status->using(WithdrawalEnum::SP_STATUS)->dot(['primary', 'danger', 'success']);
            $show->amount_type->using(WithdrawalEnum::AMOUNT_TYPE)->dot([
                1 => 'success', 2 => 'primary', 3 => 'danger'
            ]);
            $show->bank_user;
            $show->bank_name;
            $show->bank_number;
            $show->bank_address;
            $show->notes;
            $show->created_at;
            $show->updated_at;
        });
    }


    /**
     * Create interface.
     *
     * @param  Content  $content
     *
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->title('投出申请')
            ->description(' ')
            ->body(function ($row) {
//                $row->column(4, new TotalAdminUsers());
//                $row->column(4, new NewUsers());
//                $row->column(4, new NewDevices());
            })
            ->row(function (Row $row) {

                $row->column(6, function (Column $column) {

                    $column->append($this->form());
                });
            });
    }


    /**
     * Edit interface.
     * @param  mixed  $id
     * @param  Content  $content
     *
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->title('审核投出')
            ->description('审核')
            //->body($this->form()->edit($id))
            ->row(function (Row $row) use ($id) {
                $row->column(12, function (Column $column) use ($id) {
                    $column->append($this->form()->edit($id));
                });
            });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Withdrawal('admin_user'), function (Form $form) {
            $form->title('投出信息');
            $form = $this->formButton($form);
            $form->disableViewButton();
            $form->disableDeleteButton();

            $form->text('user_id')->disable()->customFormat(function ($value) {
                return $this->admin_user['name'];
            });
//            $form->text('amount_type')->disable();
            $form->text('amount_type')->customFormat(function ($value) {
                return WithdrawalEnum::AMOUNT_TYPE[$value];
            })->disable();

            $form->text('bank_user')->disable();
            if ($form->model()->type == 1) {
                $form->text('bank_name')->disable();
                $form->text('bank_number')->disable();
                $form->text('bank_address')->disable();
            } else {
                $form->text('usdt_id')->disable();
                $form->image('usdt_img')->default(function () {
                    return [$this->usdt_img];
                })->disable();
            }

            if ($form->model()->sp_status != 0) {
                $form->radio('sp_status')
                    ->options(['1' => WithdrawalEnum::SP_STATUS[1], '2' => WithdrawalEnum::SP_STATUS[2]])
                    ->disable();
            } else {
                $form->radio('sp_status')
                    ->options([
                        '1' => WithdrawalEnum::SP_STATUS[1], '2' => WithdrawalEnum::SP_STATUS[2]
                    ])->customFormat(function ($value) {
                        return 1;
                    });
            }
            if ($form->model()->sp_status != 0) {
                $form->disableSubmitButton();
                $form->disableResetButton();
            }
            // 设置默认卡片宽度
            $form->setDefaultBlockWidth(6);

            $form->block(6, function (Form\BlockForm $form) {
                $form->title('投投出额');
                $form->text('usd_amount')->disable();
                $form->text('del_amount')->disable();
                $form->text('rmb_amount_received')->disable();
                $form->text('rate')->disable();
                $form->textarea('notes')->disable();

            });
            $form->hidden('admin_id')->customFormat(function () {
                return \Admin::user()->id;
            });

//            $form->saving(function (Form $form) {
//                //$form->admin_id = \Admin::user()->id;
//                $form->admin_id = $form->admin_ids;
//                $form->deleteInput('admin_ids');
//                //dd(123, request()->all());
//            });

            $form->saved(function (Form $form, $result) {
                if (!$result) {
                    return $form->error(trans('withdrawal.fields.shsbshzs'));
                }

                // 获取保存后的整条数据
                $withdrawal = $form->repository()->eloquent();

                if ($withdrawal->sp_status == 1) {// 驳回

                    return WithdrawalHandler::refundUserMoney($withdrawal, '审核不通过');
                } elseif ($withdrawal->sp_status == 2) {// 通过

                    return WithdrawalHandler::upUserCommission($withdrawal, '审核通过');
                }
            });
        });
    }
}
